package com.net.xpay.web.controller.merchant;

import com.google.common.base.Strings;
import com.net.common.exception.BusinessException;
import com.net.common.model.ResultData;
import com.net.xpay.common.domain.User;
import com.net.xpay.core.constant.PoseidonErrorCode;
import com.net.xpay.web.secutiry.RequestUser;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.util.IOUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;

/**
 * 2020/5/7 13:31

 */
@RestController
@Slf4j
@RequestMapping("/merchant/excel")
@Api(tags = "商户/模板", description = "商户 模板 net")
public class ExcelTplController {

    /**
     * excel模板下载
     */
    @ApiOperation("excel模板下载")
    @GetMapping("/pay-trans-tpl")
    public ResultData<Boolean> export(@ApiIgnore HttpServletRequest request, @ApiIgnore HttpServletResponse response, @ApiIgnore @RequestUser User merchant) {
        String template = "手动导入打款名单模板.xls";

        getFileTemplate(template, request, response);

        return new ResultData<>(true);
    }

    /**
     * 自动付excel模板下载
     */
    @ApiOperation("自动付excel模板下载")
    @GetMapping("/auto-pay-tpl")
    public ResultData<Boolean> exportAutoPayTpl(@ApiIgnore HttpServletRequest request, @ApiIgnore HttpServletResponse response, @ApiIgnore @RequestUser User merchant) {
        String template = "鱼塘打款名单模板.xls";

        getFileTemplate(template, request, response);

        return new ResultData<>(true);
    }

    /**
     * 安全付excel模板下载
     */
    @ApiOperation("安全付excel模板下载")
    @GetMapping("/safe-pay-trans-tpl")
    public ResultData<Boolean> downloadSafePayTransTpl(@ApiIgnore HttpServletRequest request, @ApiIgnore HttpServletResponse response, @ApiIgnore @RequestUser User merchant) {
        String template = "安全付批量转账模板.xls";

        getFileTemplate(template, request, response);

        return new ResultData<>(true);
    }

    /**
     * 安全付转账到银行卡excel模板下载
     */
    @ApiOperation("安全付excel模板下载")
    @GetMapping("/safe-pay-bank-trans-tpl")
    public ResultData<Boolean> downloadSafePayBankTransTpl(@ApiIgnore HttpServletRequest request, @ApiIgnore HttpServletResponse response, @ApiIgnore @RequestUser User merchant) {
        String template = "安全付批量转账到银行卡模板.xls";

        getFileTemplate(template, request, response);

        return new ResultData<>(true);
    }

    /**
     * 批量查淘客excel模板下载
     */
    @ApiOperation("批量查淘客excel模板下载")
    @GetMapping("/batch-detection-taoke")
    public ResultData<Boolean> downloadBatchDetectionTaokeTpl(@ApiIgnore HttpServletRequest request, @ApiIgnore HttpServletResponse response, @ApiIgnore @RequestUser User merchant) {
        String template = "批量查淘客下单模板.xls";

        getFileTemplate(template, request, response);

        return new ResultData<>(true);
    }

    private void getFileTemplate(String name, HttpServletRequest request, HttpServletResponse response) {
        InputStream stream = null;
        try {
            stream = getClass().getResourceAsStream("/excel/tpl/" + name);//读取文件，前端传的是.xls
            if (stream != null) {
                //火狐游览器中文文件名会有乱码,兼容火狐
                String agent = request.getHeader("USER-AGENT").toLowerCase();

                if (!Strings.isNullOrEmpty(agent) && (agent.contains("firefox") || agent.contains("safari"))) {
                    name = new String(name.getBytes(), "ISO8859-1");
                } else {
                    name = URLEncoder.encode(name, "UTF-8");
                }
                response.setContentType("application/force-download");
                response.setHeader("Content-Disposition", "attachment; filename=" + name);
                IOUtils.copy(stream, response.getOutputStream());
                response.getOutputStream().close();
            }
        } catch (IOException e) {
            log.warn("exportTemplate failed|fileName=" + name, e);
            throw new BusinessException(PoseidonErrorCode.PARAMETER_ILLEGAL, "下载模板失败，请重试");
        } finally {
            if (stream != null) {
                try {
                    stream.close();
                } catch (Exception e) {
                    log.warn("close template file error", e);
                }
            }
        }
    }
}
